package com.libraries.view.refreshload;

import java.util.Timer;
import java.util.TimerTask;

import com.libraries.view.refreshload.listener.IPullToLoadListener;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

/**
 * 自定义的布局，用来管理三个子控件，其中一个是下拉头，一个是包含内容的pullableView， 还有一个上拉头
 * 
 */
@SuppressLint("NewApi")
public class PullToLoadLayout extends RelativeLayout {
	// 初始状态
	public static final int INIT = 0;
	// 释放刷新
	public static final int RELEASE_TO_REFRESH = 1;
	// 正在刷新
	public static final int REFRESHING = 2;
	// 操作完毕
	public static final int DONE = 5;
	// 当前状态
	private int currState = INIT;
	// 刷新回调接口
	private IPullToLoadListener mListener;
	// 刷新成功
	public static final int SUCCEED = 0;
	// 按下Y坐标，上一个事件点Y坐标
	private float downY, lastY;

	// 下拉的距离。注意：pullDownY和pullUpY不可能同时不为0
	public float pullDownY = 0;
	// 上拉的距离
	private float pullUpY = 0;

	// 释放刷新的距离
	private float refreshDist = 200;
	// 释放加载的距离
	private float loadMoreDist = 200;

	private LoadTimer loadTimer;
	// 回滚速度
	public float MOVE_SPEED = 8;
	// 第一次执行布局
	private boolean isLayout = false;
	// 在刷新过程中滑动操作
	private boolean isTouch = false;
	// 手指滑动距离与下拉头的滑动距离比，中间会随正切函数变化
	private float radio = 2;

	// 下拉头
	private View refreshView;

	// 要是实现加载的View
	private View pullableView;
	// 过滤多点触碰
	private int mEvents;
	// 这两个变量用来控制pull的方向，如果不加控制，当情况满足可上拉又可下拉时没法下拉
	private boolean canPullDown = true;
	private boolean canPullUp = false;

	/**
	 * 执行自动回滚的handler
	 */
	Handler updateHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// 回弹速度随下拉距离moveDeltaY增大而增大
			MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
					/ getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
			if (!isTouch) {
				// 正在刷新，且没有往上推的话则悬停，显示"正在刷新..."
				if (currState == REFRESHING && pullDownY <= refreshDist) {
					pullDownY = refreshDist;
					loadTimer.cancel();
				} 

			}
			if (pullDownY > 0)
				pullDownY -= MOVE_SPEED;
			else if (pullUpY < 0)
				pullUpY += MOVE_SPEED;
			if (pullDownY < 0) {
				// 已完成回弹
				pullDownY = 0;
				// 隐藏下拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
				if (currState != REFRESHING )
					changeState(INIT);
				loadTimer.cancel();
			}
			// 刷新布局,会自动调用onLayout
			requestLayout();
		}

	};

	public void setOnPullLoadListener(IPullToLoadListener listener) {
		mListener = listener;
	}

	public PullToLoadLayout(Context context) {
		super(context);
		initLoadVariables(context);
	}

	public PullToLoadLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		initLoadVariables(context);
	}

	public PullToLoadLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initLoadVariables(context);
	}

	private void initLoadVariables(Context context) {
		loadTimer = new LoadTimer(updateHandler);
	}

	private void scheduleLoadTimer() {
		loadTimer.schedule(5);
	}

	/**
	 * 完成刷新操作，显示刷新结果。注意：刷新完成后一定要调用这个方法
	 */
	/**
	 * @param refreshResult
	 *            PullToRefreshLayout.SUCCEED代表成功，PullToRefreshLayout.FAIL代表失败
	 */
	public void loadMoreFinish() {
		// 刷新结果停留1秒
		new Handler() {
			@Override
			public void handleMessage(Message msg) {
				changeState(DONE);
				scheduleLoadTimer();
			}
		}.sendEmptyMessageDelayed(0, 1000);
	}


	private void changeState(int currState) {
		this.currState = currState;
	}

	/*
	 * （非 Javadoc）由父控件决定是否分发事件，防止事件冲突
	 * 
	 * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch (ev.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			canPullDown = true;
			loadTimer.cancel();
			downY = ev.getY();
			lastY = downY;
			mEvents = 0;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
		case MotionEvent.ACTION_POINTER_UP:
			// 过滤多点触碰
			mEvents = -1;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mEvents == 0) {
				if (pullDownY > 0
						|| (canPullDown()
								&& canPullDown )) {
					// 可以下拉，正在加载时不能下拉
					// 对实际滑动距离做缩小，造成用力拉的感觉
					pullDownY = pullDownY + (ev.getY() - lastY) / radio;
					if (pullDownY < 0) {
						pullDownY = 0;
						canPullDown = false;
						canPullUp = true;
					}
					if (pullDownY > getMeasuredHeight())
						pullDownY = getMeasuredHeight();
					if (currState == REFRESHING) {
						// 正在刷新的时候触摸移动
						isTouch = true;
					}
				}  else
					canPullDown = true;
			} else
				mEvents = 0;
			lastY = ev.getY();
			// 根据下拉距离改变比例
			radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight()
					* (pullDownY + Math.abs(pullUpY))));
			requestLayout();
			if (pullDownY > 0) {
				if (pullDownY <= refreshDist
						&& (currState == RELEASE_TO_REFRESH || currState == DONE)) {
					// 如果下拉距离没达到刷新的距离且当前状态是释放刷新，改变状态为下拉刷新
					changeState(INIT);
				}
				if (pullDownY >= refreshDist && currState == INIT) {
					// 如果下拉距离达到刷新的距离且当前状态是初始状态刷新，改变状态为释放刷新
					changeState(RELEASE_TO_REFRESH);
				}
			}
			// 因为刷新和加载操作不能同时进行，所以pullDownY和pullUpY不会同时不为0，因此这里用(pullDownY +
			// Math.abs(pullUpY))就可以不对当前状态作区分了
			if ((pullDownY + Math.abs(pullUpY)) > 8) {
				// 防止下拉过程中误触发长按事件和点击事件
				ev.setAction(MotionEvent.ACTION_CANCEL);
			}
			break;
		case MotionEvent.ACTION_UP:
			if (pullDownY > refreshDist || -pullUpY > loadMoreDist)
				// 正在刷新时往下拉（正在加载时往上拉），释放后下拉头（上拉头）不隐藏
				isTouch = false;
			if (currState == RELEASE_TO_REFRESH) {
				changeState(REFRESHING);
				// 刷新操作
				if (mListener != null)
					mListener.onLoadMore(this);
			} 
			scheduleLoadTimer();
		default:
			break;
		}
		// 事件分发交给父类
		super.dispatchTouchEvent(ev);
		return true;
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		if (!isLayout) {
			isLayout = true;
			// 这里是第一次进来的时候做一些初始化
			refreshView = getChildAt(0);
			pullableView = getChildAt(1);
			// 初始化下拉布局
			refreshDist = ((ViewGroup) refreshView).getMeasuredHeight();
		}
		// 改变子控件的布局，这里直接用(pullDownY + pullUpY)作为偏移量，这样就可以不对当前状态作区分
		refreshView.layout(0,
				(int) (pullDownY + pullUpY) - refreshView.getMeasuredHeight(),
				refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY));
		pullableView.layout(0, (int) (pullDownY + pullUpY),
				pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY)
						+ pullableView.getMeasuredHeight());
	}
	
	/**
	 * 判断是否可以下拉，如果不需要下拉功能可以直接return false
	 * 
	 * @return true如果可以下拉否则返回false
	 */
	public boolean canPullDown() {
//		Log.v("Logger", "canPullDown "+(pullableView instanceof AbsListView));
		if (pullableView instanceof AbsListView) {
			AbsListView absListView=(AbsListView) pullableView;
//			Log.v("Logger", "canPullDown~"+(absListView.getFirstVisiblePosition() == 0
//					&& getChildAt(0).getTop() >= 0));
			if (absListView.getCount() == 0) {
				return true;
			} else if (absListView.getFirstVisiblePosition() == 0
					&& absListView.getChildAt(0).getTop() >= 0) 
			{
				return true;
			} else
				return false;
		}
		else if (pullableView instanceof WebView) {
			if (getScrollY() == 0)
				return true;
			else
				return false;
		}
		else if (pullableView instanceof ScrollView) {
			if (getScrollY() == 0)
				return true;
			else
				return false;
		}
		else {
			return true;
		}
	}


	/**
	 * 判断是否可以上拉，如果不需要上拉功能可以直接return false
	 * 
	 * @return true如果可以上拉否则返回false
	 */
	public boolean canPullUp() {
		if (pullableView instanceof AbsListView) {
			AbsListView absListView=(AbsListView) pullableView;
			if (absListView.getCount() == 0) {
				// 没有item的时候也可以上拉加载
				return true;
			} else if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1)) {
				// 滑到底部了
				if (absListView.getChildAt(absListView.getLastVisiblePosition() - absListView.getFirstVisiblePosition()) != null
						&& absListView.getChildAt(
								absListView.getLastVisiblePosition()
										- absListView.getFirstVisiblePosition()).getBottom() <= absListView.getMeasuredHeight())
					return true;
			}
			return false;
		}
		else if (pullableView instanceof WebView) {
			WebView webView=(WebView) pullableView;
			if (webView.getScrollY() >= webView.getContentHeight() * webView.getScale()
					- webView.getMeasuredHeight())
				return true;
			else
				return false;
		}
		else if (pullableView instanceof ScrollView) {
			ScrollView scrollView=(ScrollView) pullableView;
			if (scrollView.getScrollY() >= (scrollView.getChildAt(0).getHeight() - scrollView.getMeasuredHeight()))
				return true;
			else
				return false;
		}
		else {
			return true;
		}
	}

	class LoadTimer {
		private Handler handler;
		private Timer timer;
		private LoadTask mTask;

		public LoadTimer(Handler handler) {
			this.handler = handler;
			timer = new Timer();
		}

		public void schedule(long period) {
			if (mTask != null) {
				mTask.cancel();
				mTask = null;
			}
			mTask = new LoadTask(handler);
			timer.schedule(mTask, 0, period);
		}

		public void cancel() {
			if (mTask != null) {
				mTask.cancel();
				mTask = null;
			}
		}

		class LoadTask extends TimerTask {
			private Handler handler;

			public LoadTask(Handler handler) {
				this.handler = handler;
			}

			@Override
			public void run() {
				handler.obtainMessage().sendToTarget();
			}

		}
	}

}
